package com.ternnetwork.core.service.impl.org;



import java.util.ArrayList;

import java.util.List;
import javax.annotation.Resource;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Repository;
import org.springframework.util.StringUtils;

import com.ternnetwork.commons.model.http.BaseResponse;
import com.ternnetwork.persistence.page.BootstrapGrid;
import com.ternnetwork.persistence.page.Page;
import com.ternnetwork.core.dao.org.DepartmentDao;
import com.ternnetwork.core.entity.User;
import com.ternnetwork.core.entity.org.Department;
import com.ternnetwork.core.service.org.DepartmentService;
import com.ternnetwork.core.ui.DepartmentZtree;


@Repository("departmentService")
public class DepartmentServiceImpl implements DepartmentService {
	
	
	private static final Logger log = Logger.getLogger(DepartmentServiceImpl.class);
	
	@Resource
	private DepartmentDao departmentDao;
	

	@Override
	public BaseResponse idoAdd(Department t){
	       return doAdd(t);
    }
	@Override
	public BaseResponse doAdd(Department t) {
		BaseResponse res=new BaseResponse();
        
    	if(StringUtils.isEmpty(t.getNameZh())){
			res.setMessage("操作失败，中文名称不能为空!");
			res.setStatus(0);
			return res;
		}
		if(StringUtils.isEmpty(t.getNameEn())){
			res.setMessage("操作失败，英文名称不能为空!");
			res.setStatus(0);
			return res;
		}
		if(StringUtils.isEmpty(t.getCode())){
			res.setMessage("操作失败，代码不能为空!");
			res.setStatus(0);
			return res;
		}
		if(t.getSeqNum()==null){
			res.setMessage("操作失败，排序不能为空!");
			res.setStatus(0);
			return res;
		}
		long totalCount=departmentDao.getTotalCount("select count(id) from Department where code=?1", t.getCode());
		if(totalCount>0L){
			res.setMessage("操作失败，代码已经存在!");
			res.setStatus(0);
			return res;
		}
		Department pt=departmentDao.findById(Department.class,t.getParentId());
		if(pt==null){
			res.setMessage("操作失败，父节点不存在!");
			res.setStatus(0);
		}
		departmentDao.persist(t);
		res.setMessage("操作成功!");
		res.setStatus(1);
		res.setData(t);
		return res;
	}
	@Override
	public BaseResponse idoUpdate(Department t){
		
		    return doUpdate(t);
	}
	@Override
	public BaseResponse doUpdate(Department t) {
		
		BaseResponse res=new BaseResponse();
		
		if(StringUtils.isEmpty(t.getNameZh())){
			res.setMessage("操作失败，中文名称不能为空!");
			res.setStatus(0);
			return res;
		}
		if(StringUtils.isEmpty(t.getNameEn())){
			res.setMessage("操作失败，英文名称不能为空!");
			res.setStatus(0);
			return res;
		}
		
		if(StringUtils.isEmpty(t.getCode())){
			res.setMessage("操作失败，代码不能为空!");
			res.setStatus(0);
			return res;
		}
		
		if(t.getSeqNum()==null){
			res.setMessage("操作失败，排序不能为空!");
			res.setStatus(0);
			return res;
		}
		long totalCount=departmentDao.getTotalCount("select count(id) from Department where code=?1 and id!=?2", t.getCode(),t.getId());
		
		if(totalCount>0L){
			res.setMessage("操作失败，代码已经存在!");
			res.setStatus(0);
			return res;
		}
		Department dbt=departmentDao.findById(Department.class,t.getId());
		dbt.setNameZh(t.getNameZh());
		dbt.setNameEn(t.getNameEn());
		dbt.setSeqNum(t.getSeqNum());
		dbt.setCategory(t.getCategory());
		dbt.setCode(t.getCode());
		dbt.setAddress(t.getAddress());
		dbt.setContactPerson(t.getContactPerson());
		dbt.setEmail(t.getEmail());
		dbt.setTelephone(t.getTelephone());
		dbt.setParentId(t.getParentId());
		departmentDao.saveOrUpdate(dbt);
		res.setMessage("操作成功!");
		res.setStatus(1);
		res.setData(dbt);
		return res;
	}
	@Override
	public BaseResponse idoDeleteById(long id){
		BaseResponse res=new BaseResponse();
		Department t=departmentDao.findById(Department.class, id);
		if(t==null){
			res.setMessage("操作失败，对象不存在!");
			res.setStatus(0);
			return res;
		}
		if(t.getUsers().size()>0){
			for (User user:t.getUsers()){
				user.setDepartment(null);//解除用户与该部门的关联
			}
		}
		if(t.getParentId()==0L){
			res.setMessage("操作失败，不能删除根部门!");
			res.setStatus(0);
			return res;
		}
		List<Department> resultList=departmentDao.findAll("from Department t where t.parentId=?1",id);
		if(resultList.size()>0){
			res.setMessage("操作失败，不能删除根部门!");
			res.setStatus(0);
			return res;
		}
		departmentDao.delete(t);
		res.setMessage("操作成功!");
		res.setStatus(1);
		return res;
	}
	@Override
	public List<DepartmentZtree> getZTreeJSON(){
		List<Department> result=departmentDao.findAll("from Department sm order by sm.seqNum");
		List<DepartmentZtree> treeList=new ArrayList<DepartmentZtree>();
		for(int i=0;i<result.size();i++){
			Department t=(Department)result.get(i);
			DepartmentZtree tree=new DepartmentZtree();
			tree.setId(t.getId());
			tree.setpId(t.getParentId());
			tree.setName(t.getNameZh());
			tree.setNameEn(t.getNameEn());
			tree.setSeqNum(t.getSeqNum());
			tree.setCategory(t.getCategory());
			tree.setCode(t.getCode());
			tree.setAddress(t.getAddress());
			tree.setContactPerson(t.getContactPerson());
			tree.setEmail(t.getEmail());
			tree.setTelephone(t.getTelephone());
			tree.setNameZh(t.getNameZh());
			tree.setParentId(t.getParentId());
			treeList.add(tree);
		}
		return treeList;
	}
	@Override
	public List<Department> findAll(String jpql,Object ...param){
		return departmentDao.findAll(jpql, param);
	}
	@Override
	public List<Department> findAllByCategory(String category){
		return departmentDao.findAll("from Department where category=?1", category);
	}
	@Override
	public Department findByCode(String code){
		List<Department> retVal=departmentDao.findAll("from Department where code=?1", code);
		return retVal.size()>0?retVal.get(0):null;
	}
	public Department findByName(String name){
		List<Department> retVal=departmentDao.findAll("from Department where nameZh=?1", name);
		return retVal.size()>0?retVal.get(0):null;
	}
	@Override
	public Page<Department> query(Department t,Page page){
	    StringBuffer jpql=new StringBuffer("from Department t where 1=1");
		List<Object> params=new ArrayList<Object>();
		if(!StringUtils.isEmpty(t.getNameZh())){
			params.add("%"+t.getNameZh()+"%");
			jpql.append(" and t.nameZh like?"+params.size());
		}
		if(!StringUtils.isEmpty(t.getCategory())){
			params.add(t.getCategory()+"%");
			jpql.append(" and t.category like?"+params.size());
		}
		
		if(!StringUtils.isEmpty(t.getTelephone())){
			params.add(t.getTelephone());
			jpql.append(" and t.telephone=?"+params.size());
		}
		if(!StringUtils.isEmpty(t.getCode())){
			params.add(t.getCode());
			jpql.append(" and t.code=?"+params.size());
		}
		
		if(t.getParentId()!=null&&t.getParentId()!=0L){
			params.add(t.getParentId());
			jpql.append(" and t.parentId=?"+params.size());
		}
		
		if(!StringUtils.isEmpty(t.getEmail())){
			params.add(t.getEmail());
			jpql.append(" and t.email=?"+params.size());
		}
		
    	return departmentDao.query("select count(t.id) "+jpql.toString(), jpql.toString(), page, params.toArray());
     }
	@Override
	public BootstrapGrid queryToBootstrapGrid(Department t,Page page){
		Page<Department> result=query(t, page);
		setParentName(result);
		BootstrapGrid grid=new BootstrapGrid(result);
		return grid;
	}
	@Override
	public Department findById(Long id){
		return departmentDao.findById(Department.class, id);
	}
	@Override
	public void setParentName(Page<Department> page){
		List<Department>  list=page.getResult();
		for(Department t:list){
     		Department p=findById(t.getParentId());
			if(p!=null){
				t.setParentName(p.getNameZh());
			}
			
		}
		page.setResult(list);
	}
	@Override
	public List<Department> findAllByLikeName(String name){
		StringBuffer jpql=new StringBuffer("from Department t where 1=1");
		List<Object> params=new ArrayList<Object>();
	    params.add("%"+name+"%");
	    jpql.append(" and t.nameZh like?"+params.size());
	    jpql.append(" and t.code is not null order by t.nameZh asc");
		return departmentDao.findAll(jpql.toString(), params.toArray());
	}
	

	
}
